package com.gitee.feizns.explore.data_structure.stack.min_stack.test;

import java.util.Stack;

/**
 * @author feizns
 * @since 2019/10/12
 */
public class MinStack {

    public static void main(String[] args) {
        MinStack stack = new MinStack();
        stack.push(3);
        System.out.println(stack.getMin());
        stack.push(4);
        System.out.println(stack.getMin());
        stack.stackMin.pop();
    }

    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public MinStack() {
        this.stackData = new Stack<>();
        this.stackMin = new Stack<>();
    }

    public void push(int x) {
        this.stackData.push(x);
        if (this.stackMin.isEmpty() || x <= this.getMin()) {
            this.stackMin.push(x);
        }
    }

    public void pop() {
        if (this.stackData.isEmpty())
            throw new RuntimeException("Your stack is empty.");
        int val = this.stackData.pop();
        if (val == this.getMin())
            this.stackMin.pop();
    }

    public int top() {
        if (this.stackData.isEmpty())
            throw new RuntimeException("Your stack is empty.");
        return this.stackData.peek();
    }

    public int getMin() {
        if (this.stackMin.isEmpty())
            throw new RuntimeException("Your stack is empty.");
        return this.stackMin.peek();
    }

}
